package com.cbtx.module_sp.ui.vm

import android.app.Application
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.cbtx.module.base.ContextManager
import com.cbtx.module.base.http.HttpManager
import com.cbtx.module.base.http.MyRequestCallBack
import com.cbtx.module.base.vm.BaseVM
import com.cbtx.module.common.http.HttpUrlManager
import com.cbtx.module_sp.MachineFactory
import com.cbtx.module_sp.MyApplication
import com.cbtx.module_sp.R
import com.cbtx.module_sp.bean.IMachine
import com.cbtx.module_sp.bean.Register
import com.cbtx.module_sp.bean.Report
import com.cbtx.module_sp.bean.RequestException
import com.cbtx.module_sp.interceptor.HeaderInterceptor
import com.txcb.lib.base.utils.SharedPreferencesUtils
import com.txcb.lib.base.utils.ZxingUtils

class StartActivityVM(application: Application) : BaseVM(application) {

    val loginDataResult: MutableLiveData<Boolean> = MutableLiveData()
    val qrCodeBitmap: MutableLiveData<Bitmap> = MutableLiveData()

    /**
     * 首先获取设备Token
     */
    fun requestLoginAuth() {
        var map = mutableMapOf<String, Any>()
        var iMachine = MachineFactory.getAutoCreate(mApplication)
        map["intranetIP"] = iMachine.ip
        map["imsi"] = iMachine.imsi
        map["totalStorage"] = iMachine.totalExternalMemorySize
        map["availableStorage"] = iMachine.availableExternalMemorySize
        map["temperature"] = iMachine.temperature
        map["humidity"] = iMachine.humidity
        map["lastRebootTime"] = MyApplication.rebootTime

        val url = "${HttpUrlManager.REPORT}"
        HttpManager.getInstance("",
            HeaderInterceptor(MyApplication.instance.getHeaderMap())
        )
            .sendPost(url, map, object : MyRequestCallBack<Report>() {
                override fun onSuccess(obj: Report?) {
                    when (obj?.code) {
                        RequestException.CODE_DEVICE_DID_NOT_REGISTER -> {
                            register()
                        }
                        RequestException.CODE_PERMISSION_DENIED,
                        RequestException.CODE_DEVICE_TOKEN_INVALID,
                        RequestException.CODE_DEVICE_IS_FROZEN,
                        RequestException.CODE_COMPANY_OUT_OF_SERVICE -> {
                            SharedPreferencesUtils.saveBoolean("isBind", false)
                            loginDataResult.value = false
                            qrCodeBitmap.value = getQRImage()
                        }
                        else -> {
                            SharedPreferencesUtils.saveBoolean("isBind", true)
                            loginDataResult.value = true
                        }
                    }
                }

                override fun onFailure(error: Int, msg: String?) {

                }

            })
    }

    fun register() {
        var map = mutableMapOf<String, Any>()
        map["lastRebootTime"] = MyApplication.rebootTime
        val url = "${HttpUrlManager.REGISTER}"
        HttpManager.getInstance("",
            HeaderInterceptor(MyApplication.instance.getHeaderMap())
        )
            .sendPost(url, map, object : MyRequestCallBack<Register>() {
                override fun onSuccess(obj: Register?) {
                    loginDataResult.value = true
                }

                override fun onFailure(error: Int, msg: String?) {

                }

            })
    }

    fun getQRImage(): Bitmap? {
        val wh: Int = ContextManager.getContext().resources.getDimensionPixelSize(R.dimen.dp_400)
        val iMachine: IMachine =
            MachineFactory.getAutoCreate(MyApplication.instance)
        val url: String = ContextManager.getContext().getString(
            R.string.register_qr,
            "ad.mjcmkj.com",
            if (TextUtils.isEmpty(Build.getSerial())) "" else Build.getSerial(),
            MachineFactory.getAutoCreate(ContextManager.getContext()).uniqueDeviceCode,
            "INTERACTIVE",
            iMachine.getLocalMac(),
            iMachine.getModel()
        )
        return ZxingUtils.createQRCode(
            url,
            wh,
            BitmapFactory.decodeResource(mApplication.resources, R.drawable.ic_logo_qr_code)
        )
    }


    //step 1 : 获取登录绑定过的 设备地区
    /**
     * 获取设备绑定的区域
     */
//    fun requestDeviceUserInfo() {
//        val url = "${HttpUrlManager.LOGIN_DEVICE_USERINFO}${DeviceUtil.getSerialNumber(mApplication)}"
//        HttpManager.getInstance("")
//            .sendGet(url, HashMap(), object : MyRequestCallBack<DeviceUserInfoBean>() {
//                override fun onSuccess(obj: DeviceUserInfoBean?) {
//                    if (obj != null) {
//                        SharedPreferencesUtils.saveint("areaId", obj.areaId)
//                        loginDataResult.value = true
//                    } else {
//                        loginDataResult.value = false
//                    }
//                    LogUtil.d("")
//                }
//
//                override fun onFailure(error: Int, msg: String?) {
//
//                }
//            })
//    }

}